package android.theHead;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import java.text.DecimalFormat;
import java.util.Calendar;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

// TODO: Auto-generated Javadoc
/**
 * The Class Sensors.
 */
//public class Rowmode extends Activity implements SensorEventListener{
public class Rowmode extends Activity{
	private static final int SCREEN_TIMEOUT_DELAY = 3000000;
	private View mView;
	private Window mWindow = null;
	private HeadReadings hReadings = null;
	private HeadLocationReceiver receiver = null;
	int defTimeOut = 0;
	private boolean showReadings = false;
	boolean setBrightness = true;	
	boolean setTimeout = true;
	float oldBrightness;

	String state = Environment.getExternalStorageState();
	WindowManager.LayoutParams lp;
	private DecimalFormat twoDec = new DecimalFormat("0.00");
	private DecimalFormat oneDec = new DecimalFormat("0.0");
	private DecimalFormat twoZeroDec = new DecimalFormat("00");
	private DecimalFormat timeDec = new DecimalFormat("00.00");

	private TextView tv_time;
	private TextView tv_distance;
	private TextView tv_ranking;
	private TextView tv_speed;
	private TextView tv_speed_avg;
	private TextView tv_tempo;
	private TextView tv_tempo_avg;
	private long startTime;
	private int totalTempo = 0;
	private int tempoCount = 0;
	
		
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rowmode);
        mView = findViewById(R.id.RowmodeMain);
        mView.setVisibility(View.INVISIBLE);
        Toast.makeText( this, "To view live readings choose 'Show readings' from the options menu.", Toast.LENGTH_LONG ).show();
        Toast.makeText( this, "Warning: keeping this screen visible all the time will reduce batterylife significantly.", Toast.LENGTH_LONG ).show();
        //Make activity screen as dark as possible (override brightness settings of device)
        //TODO remove if
        tv_time = (TextView) findViewById(R.id.rmTime_value);
        tv_distance = (TextView) findViewById(R.id.rmDistance_value);
        tv_ranking = (TextView) findViewById(R.id.rmRanking_value);
        tv_speed = (TextView) findViewById(R.id.rmSpeed_value);
        tv_speed_avg = (TextView) findViewById(R.id.rmSpeed_avg_value);
        tv_tempo = (TextView) findViewById(R.id.rmTempo_value);
        tv_tempo_avg  = (TextView) findViewById(R.id.rmTempo_avg_value);
        startTime = System.currentTimeMillis();
        
        if (setBrightness){
	        mWindow = getWindow();
	    	lp = mWindow.getAttributes();
	    	oldBrightness = lp.screenBrightness;
	    	lp.screenBrightness = (float) 0.01;
	    	mWindow.setAttributes(lp);
	    	Log.d("brightness","brightness set to 0.01");     	
        }
        
        /*Temporary override device settings for screen timeout. Set to 3000000 msec
         *This workaround is needed since the accelerometer sensors stop working when the display is
         *shut off on some popular devices (notably HTC devices).
         */
        //TODO make this device dependent
        //TODO remove if
        if (setTimeout){
        	defTimeOut = Settings.System.getInt(getContentResolver(), 
        			Settings.System.SCREEN_OFF_TIMEOUT, SCREEN_TIMEOUT_DELAY);
        	Settings.System.putInt(getContentResolver(), 
        			Settings.System.SCREEN_OFF_TIMEOUT, SCREEN_TIMEOUT_DELAY);
        	Log.d("screen_timeout","screen-off timeout set to 3000000 msec");
        }
	}
	

	@Override
	    public boolean onCreateOptionsMenu(Menu menu) {
	        MenuInflater inflater = getMenuInflater();
	        inflater.inflate(R.menu.rowmode_menu, menu);
	        return true;
	    }
		    
    	/* (non-Javadoc)
    	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
    	 */
    	@Override
	    public boolean onOptionsItemSelected(MenuItem item) {
	        // Handle item selection
	        switch (item.getItemId()) {
	        case R.id.show_readings:
	        	if (showReadings){        	        		
	        		mView.setVisibility(View.INVISIBLE);   
	        		lp.screenBrightness = (float) 0.01;
	        		mWindow.setAttributes(lp);
	        		showReadings = false;
	        	}
	        	else{
	        		mView.setVisibility(View.VISIBLE);        		
	        		lp.screenBrightness = oldBrightness;
	    	    	mWindow.setAttributes(lp);
	    	    	showReadings = true; 
	        	}      	

	        default:
	            return super.onOptionsItemSelected(item);
	        }
	    }
 	
    	@Override
		protected void onResume() {
		    super.onResume();
			IntentFilter filter;
			filter = new IntentFilter(BackgroundService.NEW_HEAD_READINGS);
			receiver = new HeadLocationReceiver();
			registerReceiver(receiver, filter);
		}
		
		/* (non-Javadoc)
		 * @see android.app.Activity#onDestroy()
		 */
		protected void onPause() {
			super.onPause();
			if (setTimeout){
				Settings.System.putInt(getContentResolver(), 
						Settings.System.SCREEN_OFF_TIMEOUT, defTimeOut);
			}
			unregisterReceiver(receiver); 
		}  
		public void updateFields(){
			//TODO handle time, ranking, average tempo & average speed in background service 
			long currentTime = System.currentTimeMillis();
			float timePassed = (float) ((currentTime - startTime)/60000.0);
			String time = timeDec.format(timePassed);	
			String seconds = twoZeroDec.format((int) (Integer.parseInt(time.substring(3, 5))*0.6));
			tv_time.setText(time.substring(0, 2)+":"+seconds);
			 
			tv_distance.setText(hReadings.distance+"");
			//tv_ranking.setText(hReadings.ranking+"");
			tv_speed.setText(oneDec.format(3.6*hReadings.speed));
			//tv_speed_avg.setText(oneDec.format(3.6*hReadings.speed));
			tv_tempo.setText(oneDec.format(hReadings.tempo));	
			if (hReadings.tempo > 0){
				tempoCount ++;
				totalTempo += hReadings.tempo;
				tv_tempo_avg.setText(twoDec.format((float)totalTempo/tempoCount));
			}
			

		}
		public class HeadLocationReceiver extends BroadcastReceiver {
			@Override
			public void onReceive(Context context, Intent intent) {
				hReadings = (HeadReadings) intent.getParcelableExtra(BackgroundService.HEAD_READINGS_FIELD);
				updateFields();		
			}
		}
		
}
